import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { DownOutlined, UpOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Row,
  Col,
  Input,
  DatePicker,
  Button,
  Card,
  Tabs,
  Tooltip,
  message,
  Modal,
  Progress,
  Select,
} from 'antd';
import _ from 'lodash';
import { connect } from 'dva';
import router from 'umi/router';
import queryString from 'query-string';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; // 引入头部组件
import styles from '@/utils/utils.less';
import StandardTable from '@/components/StandardTable';
import Authorized from '@/utils/Authorized';
import downloadFile from '@/utils/utils';
import HOCSelect from '@/components/AntDesign/Select';
import DeclareModal from '../../components/DeclareModal';
import SearchPersonEs from '../../components/SearchPersonEs';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;

const { confirm } = Modal;
const { Option } = Select;
@connect(({ hire, loading }) => ({
  hire,
  loading: loading.models.hire,
}))
@Form.create()
class BasicList extends PureComponent {
  state = {
    // 供应商管理 表格配置状态
    selectedRows: [],
    selectedKeys: [],
    decExcelVisible: false,
    tableLoading: false,
    excelLoading: false,
    declParam: {
      declWay: 2,
      execStep: 2,
    },
  };

  componentDidMount() {
    const {
      location,
      dispatch,
      hire: {
        pageData: { pagination },
        activeKey,
      },
    } = this.props;
    const { isMenuLink } = queryString.parse(location.search);
    const tempActiveKey = queryString.parse(location.search).activeKey || activeKey;
    dispatch({
      type: 'hire/updateModalData',
      payload: {
        activeKey: tempActiveKey,
      },
    });
    if (isMenuLink) {
      this.resetAndGeLlist(location);
    } else {
      this.getList(activeKey, pagination.current, pagination.pageSize);
    }
  }

  componentWillUnmount() {}

  // 列表获取数据
  getList(activeKey = '1', currentPage = 1, pageSize = 10, isClear = true) {
    const { dispatch, form } = this.props;

    if (isClear) {
      this.setState({
        selectedKeys: [],
        selectedRows: [],
      });
    }
    form.validateFieldsAndScroll(
      ['timeDate', 'creName', 'execState', 'empName', 'certNo'],
      (err, values) => {
        if (!err) {
          dispatch({
            type: 'hire/updateModalData',
            payload: {
              formFieldsValue: values,
              activeKey,
            },
          });
          // 处理正确入参格式
          const tempFieldsValue = this.getDateParam(values);
          const copyAll = {
            pageArg: {
              currentPage,
              pageSize,
            },
            hireState: Number(activeKey),
            ...tempFieldsValue,
          };
          dispatch({
            type: 'hire/updateModalData',
            payload: {
              copyAll,
            },
          });

          dispatch({
            type: 'hire/fetchHireList',
            payload: copyAll,
          });
        }
      }
    );
  }

  handleSelectRows = (selectedRows, selectedKeys) => {
    const newRows = _.cloneDeep(selectedRows);
    const newKeys = _.cloneDeep(selectedKeys);
    this.setState({ selectedRows: newRows, selectedKeys: newKeys });
  };

  onDeclareOk = () => {
    const {
      hire: { addDetIds },
    } = this.props;
    const { declParam } = this.state;
    downloadFile(
      {
        addDetIds,
        ...declParam,
      },
      '/osApi/insAddDet/downloadDeclDetInsAddImport',
      'POST'
    );
    this.setState({
      decExcelVisible: false,
    });
  };

  // 获取正确入参格式
  getDateParam = values => {
    const tempFieldsValue = {};
    Object.keys(values).forEach(key => {
      if (key === 'timeDate') {
        tempFieldsValue.operBeginDate =
          (values.timeDate && values.timeDate[0] && values.timeDate[0].valueOf()) || null;
        tempFieldsValue.operEndDate =
          (values.timeDate && values.timeDate[1] && values.timeDate[1].valueOf()) || null;
      } else if (key === 'creName') {
        // 处理对象结构
        tempFieldsValue[key] = values[key]?.label;
      } else {
        tempFieldsValue[key] = values[key] === undefined ? null : values[key].trim();
      }
    });
    return tempFieldsValue;
  };

  tabChange = value => {
    const { location } = this.props;
    router.push({
      pathname: location.pathname,
      query: {
        activeKey: value,
      },
    });
    this.getList(value);
  };

  reset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    form.setFieldsValue({ timeDate: null });
    dispatch({
      type: 'hire/updateModalData',
      payload: {
        formFieldsValue: {},
      },
    });
  };

  handleData = param => {
    const { dispatch } = this.props;
    dispatch({
      type: 'hire/onLineHandle',
      payload: param,
    }).then(() => {
      this.setState({
        selectedKeys: [],
        selectedRows: [],
      });
    });
  };

  signHandleData = param => {
    const { dispatch } = this.props;
    dispatch({
      type: 'hire/markHireComplete',
      payload: param,
    }).then(() => {
      this.setState({
        selectedKeys: [],
        selectedRows: [],
      });
    });
  };

  showConfirm = selectedRows => {
    const {
      hire: { formFieldsValue, activeKey },
    } = this.props;
    const inParam = selectedRows.length
      ? { insEmpHireRetiredIds: this.getIdsArr(selectedRows), hireState: Number(activeKey) }
      : { formFieldsValue, hireState: Number(activeKey) };
    const title = selectedRows.length ? (
      <Fragment>
        <span className="emphasize-text">{selectedRows.length}</span>条
      </Fragment>
    ) : (
      '全部'
    );

    confirm({
      title: (
        <div>
          是否对当前列表{title}
          数据进行网上申报？
        </div>
      ),
      icon: <QuestionCircleOutlined />,
      okText: '是',
      cancelText: '否',
      onOk: () => {
        this.handleData(inParam);
      },
    });
  };

  showHandleConfirm = selectedKeys => {
    const {
      hire: { activeKey },
    } = this.props;
    // const inParam = { insEmpOrdIdList: selectedKeys };
    const inParam = selectedKeys;
    const tip = Number(activeKey) === 1 ? '待办理' : '办理失败';
    if (!selectedKeys.length) {
      message.warning(`请选择${tip}列表数据`);
      return;
    }
    const title = (
      <Fragment>
        <span className="emphasize-text">{selectedKeys.length}</span>条
      </Fragment>
    );

    confirm({
      title: (
        <div>
          是否对当前列表{title}
          数据进行标记已办理？
        </div>
      ),
      okText: '是',
      cancelText: '否',
      onOk: () => {
        this.signHandleData(inParam);
      },
    });
  };

  // 网上办理
  onLineHandle = () => {
    const {
      hire: {
        pageData: {
          pagination: { total },
        },
      },
    } = this.props;
    const { selectedRows } = this.state;
    if (!total) {
      message.warning('无用工数据可供操作');
    } else {
      this.showConfirm(selectedRows);
    }
  };

  pageChange = (current, pageSizes) => {
    this.getDeclList(current, pageSizes);
  };

  pageSizeChange = (current, pageSizes) => {
    this.getDeclList(current, pageSizes);
  };

  getDeclList = (currentPage, pageSize, addDetIdsParam) => {
    const {
      dispatch,
      hire: { addDetIds },
    } = this.props;
    const { declParam } = this.state;
    this.setState({
      tableLoading: true,
    });
    dispatch({
      type: 'hire/fetchDeclList',
      payload: {
        addDetIds: addDetIdsParam || addDetIds,
        ...declParam,
        // pagerArg: {
        //   currentPage,
        //   pageSize,
        // },
      },
    }).then(() => {
      this.setState({
        decExcelVisible: true,
        tableLoading: false,
      });
    });
  };

  // 申报明细表导出
  exportDetail = () => {
    const {
      dispatch,
      hire: {
        formFieldsValue,
        activeKey,
        pageData: { list },
      },
    } = this.props;
    const { selectedRows } = this.state;
    if (list.length > 0) {
      dispatch({
        type: 'hire/exportDeclResultDet',
        payload: {
          ...formFieldsValue,
          hireState: Number(activeKey),
          insEmpHireRetiredIds: this.getIdsArr(selectedRows),
        },
      }).then(res => {
        this.getDeclList(1, 5, res);
      });
    } else {
      message.warning('无查询结果，不可导出！');
    }
  };

  // 下载
  download = (url, param) => {
    downloadFile(param, url, 'POST');
  };

  // 获取id集合
  getIdsArr = selectedRows =>
    selectedRows.map(item => ({
      insEmpHireRetiredId: item.insEmpHireRetiredId,
    }));

  // 导出excel
  exportExcel = () => {
    const {
      hire: { formFieldsValue, activeKey },
    } = this.props;
    const { selectedKeys, selectedRows } = this.state;

    const obj = {
      ...formFieldsValue,
      hireState: Number(activeKey),
      insEmpHireRetiredIds: this.getIdsArr(selectedRows),
    };
    if (selectedKeys.length) {
      this.setState({ excelLoading: true });
      downloadFile(obj, '/osApi/insAddDetExt/exportExcel', 'POST', () => {
        this.setState({ excelLoading: false });
      });
    } else {
      confirm({
        title: '请选择数据，如不选择，默认导出当前条件下所有数据！',
        icon: <QuestionCircleOutlined />,
        okText: '导出',
        cancelText: '取消',
        onOk: () => {
          downloadFile(obj, '/osApi/insAddDetExt/exportExcel', 'POST');
        },
      });
    }
  };

  downSingleClick = values => {
    const {
      hire: { addDetIds },
    } = this.props;
    const { declParam } = this.state;
    const { insDeclExportId } = values;
    downloadFile(
      {
        addDetIds,
        ...declParam,
        insDeclExportId,
      },
      '/osApi/insAddDet/insAddDeclDetSingleExport',
      'POST'
    );
  };

  toggleForm = () => {
    const {
      dispatch,
      hire: { expandForm },
    } = this.props;
    dispatch({
      type: 'hire/updateModalData',
      payload: {
        expandForm: !expandForm,
      },
    });
  };

  // 标记已办理
  signHandle = () => {
    const {
      hire: {
        pageData: {
          pagination: { total },
        },
      },
    } = this.props;
    const { selectedKeys } = this.state;
    if (!total) {
      message.warning('无用工数据可供操作');
    } else {
      this.showHandleConfirm(selectedKeys);
    }
  };

  onDeclareCancel = () => {
    this.setState({
      decExcelVisible: false,
    });
  };

  handleStandardTableChange = pagination => {
    const {
      hire: { activeKey },
    } = this.props;
    this.getList(activeKey, pagination.current, pagination.pageSize, false);
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    const { dispatch } = this.props;
    await this.reset();
    await this.getList(location.query.activeKey);
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  render() {
    const formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
    const {
      form,
      hire: {
        pageData,
        expandForm,
        activeKey,
        progressPercent,
        hireStateList,
        declData,
        formFieldsValue,
        execStateList,
        showProgress,
      },
      loading,
    } = this.props;
    const { selectedRows, selectedKeys, decExcelVisible, tableLoading, excelLoading } = this.state;
    const { getFieldDecorator } = form;
    const columns = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', minWidth: 80, maxWidth: 120 } }),
      },
      {
        title: '证件号',
        dataIndex: 'certNo',

        onCell: () => ({ style: { minWidth: 130, wordBreak: 'break-all', textAlign: 'center' } }),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
      },
      {
        title: '入职日期',
        dataIndex: 'entryDate',
        onCell: () => ({ style: { textAlign: 'center' } }),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        render: text => (text ? moment(text).format('YYYY-MM-DD') : '--'),
      },
      {
        title: '业务开始日期',
        dataIndex: 'beginDate',
        onCell: () => ({ style: { textAlign: 'center' } }),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        render: text => (text ? moment(text).format('YYYY-MM-DD') : '--'),
      },
      {
        title: '申报状态',
        dataIndex: 'execStateName',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            textAlign: 'center',
            fontWeight: 'bold',
          },
        }),
        render: text => text || '--',
      },
      {
        title: '所属客服',
        dataIndex: 'creName',
        onCell: () => ({ style: { textAlign: 'center' } }),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
      },
      {
        title: '网报反馈',
        dataIndex: 'hireExexFdbk',
        className: Number(activeKey) === 4 ? styles.show : styles.hide,
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (
          <Tooltip title={text}>
            <span
              style={{
                display: 'inline-block',
                width: 140,
                textOverflow: 'ellipsis',
                overflow: 'hidden',
                whiteSpace: 'nowrap',
              }}
            >
              {text || '--'}
            </span>
          </Tooltip>
        ),
      },
      {
        title: '操作时间',
        dataIndex: 'operTime',
        onCell: () => ({ style: { textAlign: 'center' } }),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        render: text =>
          text ? (
            <span style={{ minWidth: 60 }}>{moment(text).format('YYYY-MM-DD HH:mm')}</span>
          ) : (
            '--'
          ),
      },
    ];

    const tabArr1 = (
      <Authorized authority="os:insAddDetExt:syncInsOnLineHireDecl" noMatch={null}>
        <Button type="primary" onClick={this.onLineHandle} style={{ marginRight: 8 }}>
          网上办理
        </Button>
        <Button onClick={this.signHandle} style={{ marginRight: 8 }}>
          标记已办理
        </Button>
      </Authorized>
    );
    const tabArr2 = <div />;
    const tabArr3 = (
      <Authorized authority="os:insAddDetExt:exportDeclResultDet" noMatch={null}>
        <Button style={{ marginRight: 8 }} onClick={this.exportDetail} type="primary">
          申报明细表导出
        </Button>
      </Authorized>
    );
    const tabArr4 = (
      <Fragment>
        <Authorized authority="os:insAddDetExt:syncInsOnLineHireDecl" noMatch={null}>
          <Button style={{ marginRight: 8 }} onClick={this.onLineHandle} type="primary">
            网上办理
          </Button>
        </Authorized>
        <Button onClick={this.signHandle} style={{ marginRight: 8 }}>
          标记已办理
        </Button>
        <Authorized authority="os:insAddDetExt:exportExcel" noMatch={null}>
          <Button style={{ marginRight: 8 }} onClick={this.exportExcel} loading={excelLoading}>
            导出excel
          </Button>
        </Authorized>
      </Fragment>
    );
    const tabArr = [tabArr1, tabArr2, tabArr3, tabArr4];

    const renderAdvancedForm = (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="姓名" {...formItemLayout}>
              {getFieldDecorator('empName', {
                initialValue: formFieldsValue.empName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="证件号" {...formItemLayout}>
              {getFieldDecorator('certNo', {
                initialValue: formFieldsValue.certNo,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="申报状态" {...formItemLayout}>
              {getFieldDecorator('execState', {
                initialValue: formFieldsValue.execState,
              })(
                <HOCSelect
                  placeholder="请选择"
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  style={{ width: '100%' }}
                >
                  {execStateList.map(value => (
                    <Option value={value.itemCode} key={value.itemCode}>
                      {value.itemName}
                    </Option>
                  ))}
                </HOCSelect>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="操作时间" {...formItemLayout}>
              {getFieldDecorator('timeDate', {
                initialValue: formFieldsValue.timeDate,
              })(<RangePicker style={{ width: '100%' }} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            {/* 20200921 后端要求表单改为下拉框选中项的label值 */}
            <FormItem {...formItemLayout} label="所属客服">
              {getFieldDecorator('creName', {
                initialValue: formFieldsValue.creName,
              })(
                <SearchPersonEs
                  allowClear
                  showSearch
                  // 添加labelInValue可以把选中对象到处到表单中
                  labelInValue
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <div style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" htmlType="submit" onClick={() => this.getList(activeKey)}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={() => this.reset()}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起
                  <UpOutlined />
                </a>
              </div>
            </div>
          </Col>
        </Row>
      </Form>
    );
    const renderSimpleForm = (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} label="姓名">
              {getFieldDecorator('empName', {
                initialValue: formFieldsValue.empName,
                rules: [{ required: false }],
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...formItemLayout} label="证件号">
              {getFieldDecorator('certNo', {
                initialValue: formFieldsValue.certNo,
                rules: [{ required: false }],
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={() => this.getList(activeKey)}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={() => this.reset()}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
    const renderForm = expandForm ? renderAdvancedForm : renderSimpleForm;

    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{renderForm}</div>
        </Card>
        <Card className={styles.tabCard}>
          <div className={styles.tableList}>
            <Tabs activeKey={activeKey} onChange={this.tabChange}>
              {hireStateList.map((value, index) => (
                <TabPane tab={value.itemName} key={value.itemCode}>
                  {tabArr[index]}
                  <StandardTable
                    selectedRows={selectedRows}
                    loading={loading}
                    selectedRowKeys={selectedKeys}
                    data={pageData}
                    columns={columns}
                    rowKey="insEmpHireRetiredId"
                    onSelectRow={this.handleSelectRows}
                    onChange={this.handleStandardTableChange}
                    style={{ marginTop: 16 }}
                  />
                </TabPane>
              ))}
            </Tabs>
          </div>
        </Card>
        <Modal title="网上办理" footer={null} closable={false} visible={showProgress}>
          <div style={{ textAlign: 'center' }}>
            <div>
              <Progress
                percent={progressPercent}
                format={percent => `${percent}%`}
                style={{ paddingRight: 24, marginBottom: 20 }}
              />
            </div>
          </div>
        </Modal>
        <DeclareModal
          visible={decExcelVisible}
          dataSource={declData}
          tableLoading={tableLoading}
          downSingleClick={this.downSingleClick}
          onCancel={this.onDeclareCancel}
          pageChange={this.pageChange}
          pageSizeChange={this.pageSizeChange}
          onOk={this.onDeclareOk}
          declExportId="insDeclExportId"
          accoName="insAccoName"
          downLoadDeclErr={this.download}
        />
      </PageHeaderWrapper>
    );
  }
}

export default BasicList;
